﻿
using Light.Framework.Component;
using Light.Coin.Model;
using Light.Coin.Contract;
using Light.Framework.Model;
using Light.Utility;
using System;
using Light.Framework.Castle;
using Light.Framework;

namespace Light.Coin.Component
{
    public class SignLogComponent : BaseComponent<SignLog>, ISignLogComponent
    {
        public OperateResult Sign()
        {
            SignLog log = new SignLog();
            return Create(log);
        }

        public override OperateResult Create(SignLog obj)
        {
            /*
             * 1.检查用户今天是否已签到
             * 2.计算连续签到天数
             * 3.计算积分
             */

            OperateResult result = new OperateResult();
            SignLog latest = Get();

            if (latest != null && latest.TimeCreated.Date == DateTime.Now.Date)
            {
                result.Message = "今天已经签过到了，明天再来吧";
                result.IsSucced = false;
                return result;
            }
            else if (latest != null)
            {
                if (latest.TimeCreated.Date == DateTime.Now.Date.AddDays(-1))
                {
                    obj.LastDays = latest.LastDays + 1;
                }
            }
            /*
             * 第一天签到获取1分
             * 连续第二天签到获取3分
             * 连续第三天签到获取5分
             * 此后连续签到获取10分
             * 有中断，则从1分起算
             */
            if (obj.LastDays == 1)
                obj.Coins = 1;
            else if (obj.LastDays == 2)
                obj.Coins = 3;
            else if (obj.LastDays == 3)
                obj.Coins = 5;
            else
                obj.Coins = 10;

            if (obj.User == null)
                obj.User = (User)ServerApplication.User;

            obj.User.TimeSigned = DateTime.Now;
            result = base.Create(obj);

            if (result.IsSucced)
            {
                ICoinLogComponent coinComp = ServerApplication.ComponentFactory.Create<ICoinLogComponent>();
                CoinLog coinLog = new CoinLog();
                coinLog.User = obj.User;
                coinLog.Source = CoinSource.Sign;
                coinLog.SourceID = obj.ID;
                coinLog.Coins = obj.Coins;
                coinComp.Create(coinLog);

                result.Message = JsonConverter.Serialize(obj);
            }
            return result;
        }

        /// <summary>
        /// 获取最近一次签到
        /// </summary>
        /// <returns></returns>
        public override SignLog Get()
        {
            SearchArgs args = new SearchArgs();
            args["User"] = (User)ServerApplication.User;

            ModelOrder order = new ModelOrder();
            order.Add("ID", false);

            SignLog obj = Get(args, order);
            if (obj != null)
            {
                ServerApplication.Evit(obj.User);
                ServerApplication.Evit(obj);
            }
            return obj;
        }
    }
}
